<template>
	<view class="tab" :class="{tabRow: props.isScroll}">
		<view @click="onChange(item, index)" v-for="(item, index) in props.tabList" :key="index">
			<view v-if="item.num > 0" class="red-dots">
				<text>{{ item.num }}</text>
			</view>

			<view :style="{color: active == index ? props.color : ''}">
				<view>{{ item[props.showField] }}</view>
				<view class="line" :style="{backgroundColor: active == index ? props.color : ''}"></view>
			</view>
		</view>
	</view>
</template>

<script setup name="x-tab">
	import {
		ref,
		toRefs,
		toRaw,
		watch
	} from "vue";

	const props = defineProps({
		color: {
			type: String,
			default: "#4C9DFB"
		},

		bgColor: {
			type: String,
			default: "#4C9DFB"
		},

		tabList: {
			type: Array,
			default: () => {
				return []
			}
		},

		modelValue: {
			type: Number,
			default: 0,
		},

		before: {
			type: Function
		},

		showField: {
			type: String,
			default: 'text'
		},

		isScroll: {
			type: Boolean,
			default: false
		}
	})

	const active = ref(0)

	// 分开写比较好watch无法表明是哪个触发
	watch(() => props.modelValue, (value) => {
		active.value = value
	})
	watch(active, (value) => {
		emit('update:modelValue', value)
	})

	const emit = defineEmits(['change'])
	const onChange = (tab, index) => {
		let flag = true;
		if (props.before) {
			flag = props.before(tab, index);
			if (flag instanceof Promise) {
				flag.then(c => {
					active.value = index;
					emit("change", toRaw(tab), index);
				})

				return;
			}
		}

		if (flag) {
			active.value = index;
			emit("change", toRaw(tab), index);
		}
	}
</script>

<style scoped>
	.tab {
		margin-top: 0;
		margin-bottom: 0;
		/* padding: 10rpx 0; */
		letter-spacing: 1px;
		padding-top: 0;
		background-color: #fff;
		height: 100rpx;
		line-height: 45rpx;
		display: flex;
		justify-content: space-around;
		overflow-x: auto;
	}

	/**
  兼容以前的样式，之前可能是左右排序
   */
	.tabRow {
		flex-direction: row;
		justify-content: flex-start;
	}

	.tab>view {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-shrink: 0;
		flex-wrap: nowrap;
		border-radius: 5rpx;
		margin-right: 10rpx;
		font-weight: 600;
		font-size: 28rpx;
		color: #282828;
		position: relative;
		padding: 0 10rpx;
    box-sizing: border-box;
	}

	.tab .red-dots {
		position: absolute;
		right: 0;
		top: -22rpx;
	}

	.tab .red-dots text {
		margin-right: -90%;
		margin-top: -100rpx;
		height: 26rpx;
		min-width: 18rpx;
		text-align: center;
		line-height: 26rpx;
		padding: 0 6rpx;
		border-radius: 26rpx;
		font-size: 18rpx;
		color: #fff;
		font-weight: 500;
		background-color: #fa3c36;
	}

	.line {
		/* width: 80rpx; */
		width: 80%;
		height: 5rpx;
		margin: 8rpx auto;
		border-radius: 100rpx;
	}
</style>
